package com.itheima.ums.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.mall.pojo.Resource;
import com.itheima.mall.pojo.Role;
import com.itheima.mall.vo.PageResult;
import com.itheima.ums.mapper.ResourceMapper;
import com.itheima.ums.service.UmsResourceService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class UmsResourceServiceImpl implements UmsResourceService {

    @Autowired
    private ResourceMapper resourceMapper;

    //添加后台资源
    public Integer create(Resource resource) {
        resource.setCreateTime(new Date());
        return resourceMapper.insert(resource);
    }

    //根据ID删除后台资源
    public Integer deleteById(Long id) {
        return resourceMapper.deleteById(id);
    }


    /**
     * 分页模糊查询后台资源
     *
     * @param pageNum
     * @param pageSize
     * @param nameKeyword
     * @param urlKeyword
     * @param categoryId
     * @return
     */
    public PageResult list(Integer pageNum, Integer pageSize, String nameKeyword, String urlKeyword, Long categoryId) {
        Page page = new Page(pageNum, pageSize);
        LambdaQueryWrapper<Resource> queryWrapper = new LambdaQueryWrapper<>();
        //关键字存在就匹配关键字查询
        queryWrapper.like(StringUtils.isNotEmpty(nameKeyword), Resource::getName, nameKeyword)
                .like(StringUtils.isNotEmpty(urlKeyword), Resource::getUrl, urlKeyword)
                .eq(categoryId != null, Resource::getCategoryId, categoryId);


        resourceMapper.selectPage(page, queryWrapper);

        return new PageResult(pageNum, pageNum, (int) page.getTotal(), page.getRecords());
    }

    /**
     * 查询所有后台资源
     *
     * @return
     */
    public List<Resource> listAll() {
        LambdaQueryWrapper<Resource> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Resource::getCreateTime);
        return resourceMapper.selectList(queryWrapper);

    }

    /**
     * 修改后台资源
     *
     * @param id
     * @return
     */
    public Integer updateById(Long id, Resource resource) {
        LambdaQueryWrapper<Resource> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Resource::getId, id);
        return resourceMapper.update(resource, queryWrapper);
    }

    /**
     * 根据ID获取资源详情
     *
     * @param id
     * @return
     */
    public Resource getById(Long id) {
        return resourceMapper.selectById(id);
    }
}
